package com.example.xyr.myapplication.utils

import android.app.Activity
import com.jrmf360.tools.utils.LogUtil

/**
 * Created by ylcf on 2018/8/30.
 */
class ActivityManger {

    companion object {
        val instance by lazy(LazyThreadSafetyMode.NONE) {
            ActivityManger()
        }
    }

    private val activityList: MutableList<Activity> = arrayListOf()


    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity) {
        LogUtil.e("addActivity", activity)
        for (ac in activityList) {
            if (activity == ac) {
                activityList.remove(ac)
            }
        }
        activityList.add(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            LogUtil.e("finishActivity", activity)
            activityList.remove(activity)
            activity.finish()
        }
    }

    /**
     * 找到指定的activity－如果有相同的activity － 取出来最后打开的哪个activity
     *
     * @param calzz
     * @return
     */
    fun <T> findActivity(calzz: Class<T>): T? {
        var a: Activity? = null
        for (i in activityList) {
            if (i.javaClass == calzz) {
                a = i
                break
            }
        }
        return a as T?
    }

    /**
     * 结束指定类名的Activity - 如果有相同的activity，结束最后打开的哪个activity
     */
    fun finishActivity(cls: Class<*>): Boolean {
        var isFinish = false
        for (ac in activityList) {
            if (ac.javaClass == cls) {
                finishActivity(ac)
                isFinish = true
                break
            }
        }
        return isFinish
    }

    /**
     * 获取当前Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): Activity =
            activityList[activityList.size]


    /**
     * 结束当前Activity（堆栈中最后一个压入的）
     */
    fun finishCurrActivity() {
        finishActivity(activityList[activityList.size])
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        // 关闭我们自己的页面
        for (ac in activityList) {
            ac.finish()
        }
        activityList.clear()
    }

    /**
     * 退出应用程序
     */
    fun exitApp() {
        try {
            finishAllActivity()
            System.exit(0)
            android.os.Process.killProcess(android.os.Process.myPid())
        } catch (e: Exception) {
        }
    }


}